package com.itrip.biz.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itrip.beans.pojo.*;
import com.itrip.beans.vo.*;
import com.itrip.biz.service.CommentService;
import com.itrip.biz.service.ImageService;
import com.itrip.dao.*;
import com.itrip.utils.dto.Dto;
import com.itrip.utils.vo.DtoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import static java.lang.Integer.parseInt;

/**
 * 评论
 * @Author: 周勉
 * @date: 2020/3/10 17:57
 */
@RestController
@RequestMapping(value = "/biz/api/comment")
public class CommommentController {
    @Resource
    HotelMapper hotelMapper;
    @Autowired
    private CommentService commentService;
    @Autowired
    private ImageService imageService;

    //获 取 酒 店 的总体评分、位置评分、设施评分、服务评分、卫生评分
    @GetMapping("/gethotelscore/{hotelId}")
    public Dto<HotelScoreVo> getHotelScore(@PathVariable String hotelId){
        return DtoUtil.returnSuccess("获取数据成功！",commentService.getHotelScore(parseInt(hotelId)));
    }

    //根据酒店 id查 询 评 论 数量
    @GetMapping("/getcount/{hotelId}")
    public Dto<CommentCountVo> getCount(@PathVariable String hotelId){
        return DtoUtil.returnDataSuccess(commentService.getCount(parseInt(hotelId)));
    }

    //很具条件查询相应评论
    @PostMapping("/getcommentlist")
    public Dto<PageVo<Comment>> getCommentList(@RequestBody CommentListVo vo){
        return DtoUtil.returnDataSuccess(commentService.getCommentList(vo));
    }

    //根据targetId查询评论图片(type=2)
    @GetMapping("/getimg/{targetId}")
    public Dto getImg(@PathVariable String targetId){
        QueryWrapper qw=new QueryWrapper();
        qw.eq("type",2);
        qw.eq("target_id",targetId);
        return DtoUtil.returnDataSuccess(imageService.list(qw));
    }


    @RequestMapping(value = "/gethoteldesc/{hotelId}")
    public Dto<Object> getHotelDesc(@PathVariable String hotelId){
        Dto<Object> dto = new Dto<Object>();
        ItripHotelDescVO itripHotelDescVO = null;
        try{
            if(null != hotelId && !"".equals(hotelId)){
                Hotel hotel = new Hotel();
                hotel = hotelMapper.selectById(Long.valueOf(hotelId));
                itripHotelDescVO = new ItripHotelDescVO();
                itripHotelDescVO.setHotelId(hotel.getId());
                itripHotelDescVO.setHotelName(hotel.getHotelName());
                itripHotelDescVO.setHotelLevel(hotel.getHotelLevel());
            }
            dto = DtoUtil.returnDataSuccess(itripHotelDescVO);
        }catch (Exception e){
            e.printStackTrace();
            dto = DtoUtil.returnFail("获取酒店相关信息错误");
        }

        return dto;
    }

    @Resource
    LabelDicMapper labelDicMapper;

    @RequestMapping(value = "/gettraveltype")
    public Dto<Object> getTravelType(){
        Dto<Object> dto = new Dto<Object>();
        Long parentId = 107L;
        List<ItripLabelDicVO> itripLabelDicVOList = new ArrayList<ItripLabelDicVO>();
        try {
            LabelDic labelDic =  labelDicMapper.selectById(parentId);
            dto = DtoUtil.returnSuccess("获取旅游类型列表成功",itripLabelDicVOList);
        } catch (Exception e) {
            e.printStackTrace();
            dto =  DtoUtil.returnFail("获取旅游类型列表错误");
        }
        return dto;
    }

    @Value("${upload.picture.path}")
    private String uploadPicturePath;

    int isHavingImg;

    @Resource
    ImageMapper imageMapper;


    //图片上传相关代码
    @PostMapping(value = "/upload")
    public Dto imgUpLoad(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
        MultipartHttpServletRequest multipartHttpServletRequest = null;
        //强制转换为MultipartHttpServletRequest接口对象 (它包含所有HttpServletRequest的方法)
        if(request instanceof MultipartHttpServletRequest){
            multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        }else{
            return DtoUtil.returnFail("上传失败");
        }
        //获取MultipartFile文件信息(注意参数为前端对应的参数名称)
        MultipartFile mf = multipartHttpServletRequest.getFile("file");
        //获取源文件名称
        String fileName = mf.getOriginalFilename();
        if(fileName.trim() !="" && (fileName.toLowerCase().contains(".jpg")
                                || fileName.toLowerCase().contains(".jpeg")
                                || fileName.toLowerCase().contains(".png")
                ) ) {
            //存储路径可在配置文件中指定
            File pfile = new File(uploadPicturePath);
            if (!pfile.exists()) {
                pfile.mkdirs();
            }
            File file = new File(pfile, fileName);
            try {
                //保存文件
                //使用此方法保存必须要绝对路径且文件夹必须已存在,否则报错
                mf.transferTo(file);
            } catch (IOException e) {
                e.printStackTrace();
                return DtoUtil.returnFail("上传失败");
            }
        }else {
            return DtoUtil.returnFail("请求的内容不是上传文件的类型");
        }
        Comment comment= commentService.getLastComment();
        Image image = new Image();
        isHavingImg =1;
        QueryWrapper commQueryWapper = new QueryWrapper();
        commQueryWapper.like("content","");
        image.setType("2");
        image.setImgUrl("http://img.itrip.test.com/comment/"+fileName);
        image.setTargetId(Long.parseLong(comment.getId()+1+""));
        QueryWrapper imgQueryWrapper = new QueryWrapper();
        imgQueryWrapper.eq("target_id",comment.getId());
        imgQueryWrapper.eq("type",2);
        List<Image> image1= imageMapper.selectList(imgQueryWrapper);
        image.setPosition(image1.size()+1

        );
        imageMapper.insert(image);
        return DtoUtil.returnSuccess("上传成功");
    }

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    CommentMapper commentMapper;

    @Resource
    HotelOrderMapper hotelOrderMapper;

    @PostMapping("/add")
    public Dto addComment(@RequestBody Comment comment,HttpServletRequest request){
        String token=request.getHeader("token");
        Long userId= Long.parseLong(stringRedisTemplate.opsForValue().get(token));
        comment.setUserId(userId);
        comment.setIsHavingImg(isHavingImg);
        commentMapper.insert(comment);
        HotelOrder hotelOrder =new HotelOrder();
        hotelOrder.setId(comment.getOrderId());
        hotelOrder.setOrderStatus(4);
        hotelOrderMapper.updateById(hotelOrder);

        return DtoUtil.returnSuccess("评论成功");
    }
}
